package com.votingsystem.controller;

import com.votingsystem.config.Config;
import com.votingsystem.entity.Artwork;
import com.votingsystem.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
public class MainController {

    @Autowired
    Config config;

    // 日志
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    // 是否开始投票
    private static boolean isStart = false;
    // 当前作品的下标
    private static int index = 0;
    // 作品列表
    private static List<Artwork> artworkList = new ArrayList<>();
    // 已投票
    private static Set<String> voteSet = new HashSet<>();
    // 已赞
    private static Set<String> likeSet = new HashSet<>();
    // 评委已赞
    private static Set<String> plikeSet = new HashSet<>();

    // 初始化作品
    static {
        Artwork artwork = new Artwork();
        artwork.setAuthor("蓝文华,田琦");
        artwork.setName("沙驰女鞋-探店");
        artwork.setTicket((int)(Math.random()*10 + 5));
        artwork.setRank(1);
        artworkList.add(artwork);

        Artwork artwork1 = new Artwork();
        artwork1.setAuthor("代屿,纪玉阳,张聪聪,蔺岳龙");
        artwork1.setName("简·爱");
        artwork1.setTicket((int)(Math.random()*10 + 5));
        artwork1.setRank(2);

        artworkList.add(artwork1);

        Artwork artwork2 = new Artwork();
        artwork2.setAuthor("吴淼,王孙宇,郭昭然,王雪莉,龚世飞");
        artwork2.setName("品牌探店-巴黎欧莱雅");
        artwork2.setRank(3);
        artwork2.setTicket((int)(Math.random()*10 + 5));
        artworkList.add(artwork2);

        Artwork artwork3 = new Artwork();
        artwork3.setAuthor("邸超帅,郭秀霞,孙天轶,韩璐悦");
        artwork3.setName("路易莎美探店");
        artwork3.setRank(4);
        artwork3.setTicket((int)(Math.random()*10 + 5));
        artworkList.add(artwork3);

        Artwork artwork4 = new Artwork();
        artwork4.setAuthor("刘凯越,魏帅,刘洪妤");
        artwork4.setName("哏儿都煎饼");
        artwork4.setRank(5);
        artwork4.setTicket((int)(Math.random()*10 + 5));
        artworkList.add(artwork4);

        Artwork artwork5 = new Artwork();
        artwork5.setAuthor("魏一笑,马靖钰,孙佳朋,杨金京,缪中龙");
        artwork5.setName("欧巴的分米鸡");
        artwork5.setRank(6);
        artwork5.setTicket((int)(Math.random()*10 + 5));
        artworkList.add(artwork5);

        Artwork artwork6 = new Artwork();
        artwork6.setAuthor("孟宪彤,方新泽,王文博,杜海英,牛素文");
        artwork6.setName("打卡彪马");
        artwork6.setRank(7);
        artwork6.setTicket((int)(Math.random()*10 + 5));
        artworkList.add(artwork6);

        Artwork artwork7 = new Artwork();
        artwork7.setAuthor("王越,雷柯,陈凌波");
        artwork7.setName("《我要成为海贼王》");
        artwork7.setRank(8);
        artwork7.setTicket((int)(Math.random()*10 + 5));
        artworkList.add(artwork7);

    }

    // 防止误操作的状态【有作品正在投票不能再开始投票】
    private static boolean state = true;
    // 切换作品状态锁【当前作品没有投票则不能切换下一个作品】
    private static boolean nextBlock = false;
    // 排序接口只能调用一次
    private static boolean sortBlock = true;
    // 汇总防止重票
    private static boolean repetionBlock = true;

    @GetMapping("/sort")
    public Result sort(){
        if (sortBlock){
            artworkSort();
            sortBlock = false;
        }
        return new Result(artworkList,true);
    }

    /**
     * 获取UUID
     */
    @GetMapping("/getuuid")
    public Result getUUID() {
        String replace = UUID.randomUUID().toString().replace("-", "");
        return new Result(replace, true);
    }

    /**
     * 学生投票接口
     */
    @PostMapping("/vote")
    public Result vote(String uuid, int ticket) {
        if (index >= 8) {
            return new Result(false, "所有作品都已完成投票！");
        } else if (!isStart) {
            return new Result(false, "投票还未开始！");
        } else if (voteSet.contains(uuid)) {
            return new Result(false, "您已经投过票了！");
        }
        // 投票主功能区
        voteSet.add(uuid);
        if (ticket != 0) {
            likeSet.add(uuid);
        }
        return new Result(true, "投票成功！");
    }

    /**
     * 评委投票接口
     */
    @PostMapping("/pwVote")
    public Result pwVote(String uuid, int ticket) {
        if (index >= 8) {
            return new Result(false, "所有作品都已完成投票！");
        } else if (!isStart) {
            return new Result(false, "投票未开始！");
        } else if (voteSet.contains(uuid)) {
            return new Result(false, "您已经投过票了！");
        }
        // 投票主功能区
        voteSet.add(uuid);
        if (ticket != 0) {
            plikeSet.add(uuid);
        }
        return new Result(true, "投票成功！");
    }

    /**
     * 开始投票接口
     */
    @PostMapping("/start")
    public Result start() {
        if (index > 7) {
            return new Result(false, "所有作品均已投票完毕！");
        }
        if (!state) {
            return new Result(false);
        }
        isStart = true;
        log.info("【开始投票】" + index + "号作品开始投票");
        // 开启线程一分钟后自动关闭投票
        new Thread(() -> {
            try {
                state = false;
                Thread.sleep(10 * 1000);
                // 关闭投票
                isStart = false;
                // 统计票数
                int scores = likeSet.size() + plikeSet.size() * 10;
                artworkList.get(index).setTicket(scores + artworkList.get(index).getTicket());
                likeSet.clear();
                plikeSet.clear();
                state = true;
                nextBlock = true;
                log.info("【结束投票】" + index + "号作品结束投票" + "票数为：" + scores);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        return new Result(true);
    }

    /**
     * 开始下一个
     */
    @PostMapping("/next")
    public Result next() {
        if (state && nextBlock){
            index++;
            nextBlock = false;
            return new Result(true);
        }
        return new Result(false);
    }

    /**
     * 获取当前正在投票的作品
     */
    @GetMapping("/getArtwork")
    public Result getArtwork() {
        if (index >= artworkList.size()) {
            return new Result(false, "所有作品均已投票完毕!");
        }
        return new Result(artworkList.get(index), true);
    }

    /**
     * 获取所有投票结果
     */
    @GetMapping("/getResult")
    public Result getResult() {
        if (index == artworkList.size() && repetionBlock){
            // 当所有作品都完成投票后计算排名
            getSortResult();
            repetionBlock = false;
        }
        return new Result(artworkList, true);
    }

    /**
     * 将作品排名插入
     */
    private void getSortResult() {
        List<Artwork> rankList = new ArrayList<>(artworkList);
        Collections.sort(rankList);
        for (int i = 0; i < rankList.size(); i++) {
            if (i < artworkList.size() - 3){
                rankList.get(i).setTicket(rankList.get(i).getTicket() - 3);
            }else {
                rankList.get(i).setTicket(rankList.get(i).getTicket() - (artworkList.size() - 1 - i));
            }

        }
        for (Artwork item : artworkList) {
            for (int i = 0; i < rankList.size(); i++) {
                if (item.getName().equals(rankList.get(i).getName())){
                    item.setTicket(rankList.get(i).getTicket());
                    item.setRank(artworkList.size() - i);
                    break;
                }
            }
        }
    }

    // 自定义顺序
    private void artworkSort(){
        String[] order = config.getArtworksort().split(",");
        // 排顺序用的临时列表
        List<Artwork> artworkSort = new ArrayList();
        int[] arr = new int[9];
        for (int i = 0; i < order.length; i++) {
            int sx = Integer.parseInt(order[i]);
            arr[sx] = i;
        }
        for (int i = 1; i < arr.length; i++) {
            artworkSort.add(artworkList.get(arr[i]));
        }
        artworkList.clear();
        artworkList.addAll(artworkSort);
    }
}
